from common import AlsoLikeEntity,SearchFilter
import DatabaseConnection

class AlsoLikeData(object):
    def __init__(self):
        pass

    def InsertAlsoLike(self,alsoLike):
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('InsAlsoLike',(alsoLike.AlbumID,alsoLike.LikeID))
        cursor.close()
        conn.commit()
        conn.close()

    def UpdateAlsoLike(self,alsoLike):
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('UpdAlsoLike',(alsoLike.AlbumID,alsoLike.LikeID))
        cursor.close()
        conn.commit()
        conn.close()

    def DeleteAlsoLike(self,aID,lID):
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('DelAlsoLike',(ID,lID,))
        cursor.close()
        conn.commit()
        conn.close()

    #This method either return an object of type AlsoLikeEntity or None (if there is no record with this ID)
    def SelectAlsoLikeByID(self,aID,lID):
        query = """ SELECT AlbumID,LikeID,AlbumName,LikeAlbumName
                    FROM vwAlsoLike
                    WHERE AlbumID='%s' AND LikeID='%s'""" % (aID,lID)

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        if len(result) <> 0:
            return AlsoLikeEntity.AlsoLikeEntity(albumID=result[0][0],likeID=result[0][1],albumName=result[0][2],likeAlbumName=result[0][3])
        else:
            return None

    #This method returns a list of objects of type AlsoLikeEntity
    def SelectAlsoLikeByFilter(self,searchFilter):
        query = """ SELECT AlbumID,LikeID,AlbumName,LikeAlbumName
                    FROM vwAlsoLike"""

        whereClause = searchFilter.GetWhereClause()
        if whereClause.strip()<>"":
            query += " WHERE %s" % whereClause

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        recordSet = []
        for record in result:
            recordSet.append(AlsoLikeEntity.AlsoLkeEntity(albumID=record[0],likeID=record[1],albumName=record[2],likeAlbumName=record[3]))
        return recordSet

    def SelectAllAlsoLikes(self):
        query = """ SELECT AlbumID,LikeID,AlbumName,LikeAlbumName
                    FROM vwAlsoLike"""

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        recordSet = []
        for record in result:
            recordSet.append(AlsoLikeEntity.AlsoLkeEntity(albumID=record[0],likeID=record[1],albumName=record[2],likeAlbumName=record[3]))
        return recordSet
